import axios, { AxiosError } from 'axios';
import type { AxiosInstance, InternalAxiosRequestConfig } from 'axios';
import { ElMessage } from 'element-plus'

import { useUserStore } from '@/stores/user';

const service: AxiosInstance = axios.create({
    baseURL: "http://pudding1201.com:80/api/v1",
    // baseURL: `${import.meta.env.VITE_BACKEND_URL}`,
    timeout: 5000
});

service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        const userStore = useUserStore();
        config.data = JSON.stringify(config.data);
        config.headers.set('Content-type', 'application/json');

        if (userStore.isLogin) {
            config.headers.set('x-token', userStore.token);
            config.headers.set('x-user-id', userStore.userId);
        }

        return config;
    },
    // (error: AxiosError) => {
    //     console.log(error);
    //     return Promise.reject();
    // }
    (error: any) => {
        ElMessage({
            message: error,
            type: 'error',
            center: true
        })
        return error
    }
);

service.interceptors.response.use(
    (response: any) => {
        if (response.status === 200) {
            // if (response.headers['new-token']) {
            //     const userStore = useUserStore();
            //     userStore.setToken(response.headers['new-token'])
            // }
            return response.data as any;
        } else {
            // Promise.reject();
        }
    },
    // 
    (error: any) => {
        ElMessage({
            message: error,
            type: 'error',
            center: true
        })
        return error
    }
);

export default service;
